package com.yyt.springbootdemoredis.controller;

import com.yyt.springbootdemoredis.pojo.User;
import com.yyt.springbootdemoredis.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

/**
 * @author: yeyangtao
 * @date: 2019/12/3 11:11
 */
@RequestMapping("/redis")
@RestController
@Slf4j
public class RedisController {
    /**
     * redis存储过期时间
     */
    private static int EXPIRETIME = 60;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 存入key，value
     *
     * @param key
     * @param value
     * @return boolean
     */
    @RequestMapping("/set")
    public boolean redisSet(String key, String value) {
        User user = new User(1L, "1", "zhangsan", "20", new Date());
        return redisUtil.set(key, value);
    }

    /**
     * 根据key获取value
     *
     * @param key
     * @return java.lang.Object
     */
    @RequestMapping("/get")
    public Object redisGet(String key) {
        return redisUtil.get(key);
    }

    /**
     * 根据key判断是否失效
     *
     * @param key
     * @return boolean
     */
    @RequestMapping("expire")
    public boolean expire(String key) {
        return redisUtil.expire(key, EXPIRETIME);
    }

    /**
     * RedisSession，session存到redis中
     *
     * @param session
     * @return java.lang.String
     */
    @RequestMapping("/uid")
    public String uid(HttpSession session) {
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }
        session.setAttribute("uid", uid);
        return session.getId();
    }

}
